package com.zwb.demo.easyweb.modules.config.service.impl;

import com.zwb.demo.easyweb.common.entity.response.CommonCode;
import com.zwb.demo.easyweb.common.entity.response.ResponseResult;
import com.zwb.demo.easyweb.core.exception.ExceptionCast;
import com.zwb.demo.easyweb.core.utils.ConvertUtils;
import com.zwb.demo.easyweb.modules.config.entity.FormValidatePO;
import com.zwb.demo.easyweb.modules.config.repository.FormValidatePORepository;
import com.zwb.demo.easyweb.modules.config.service.FormValidateService;
import com.zwb.demo.easyweb.modules.config.vo.FormValidateVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 校验表
 *
 * @author zwb
 * @date 2020-04-26T14:56:54.008456400
 */
@Service
public class FormValidateServiceImpl implements FormValidateService {
    private final FormValidatePORepository formValidateRepository;

    @Autowired
    public FormValidateServiceImpl(FormValidatePORepository formValidateRepository) {
        this.formValidateRepository = formValidateRepository;
    }
    

    @Override
    public ResponseResult saveOne(FormValidateVO vo) {
        if (StringUtils.isNotBlank(vo.getId())){
            Optional<FormValidatePO> optional = formValidateRepository.findById(vo.getId());
            if (!optional.isPresent()){
                ExceptionCast.cast(CommonCode.ID_NO_EXITS);
            }
            FormValidatePO po = optional.get();
            BeanUtils.copyProperties(vo, po);
            formValidateRepository.save(po);
        }else {
            FormValidatePO po = ConvertUtils.convertObject(vo, FormValidatePO.class);
            formValidateRepository.save(po);
        }
        return ResponseResult.ok();
    }

    @Override
    public ResponseResult deleteOne(String uuid) {
        if (StringUtils.isBlank(uuid)){
            ExceptionCast.cast(CommonCode.ILLEGAL_PARAM);
        }
        formValidateRepository.deleteById(uuid);
        return ResponseResult.ok();
    }

    @Override
    public ResponseResult findAll() {
        List<FormValidatePO> allPO = formValidateRepository.findAll();
        List<FormValidateVO> allVO = ConvertUtils.convertList(allPO, FormValidateVO.class);
        return ResponseResult.ok().body(allVO);
    }
}
